package kadledav.adventure.framework.controll;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import kadledav.adventure.framework.controll.commands.DropCommand;
import kadledav.adventure.framework.controll.commands.ExploreCommand;
import kadledav.adventure.framework.controll.commands.GoCommand;
import kadledav.adventure.framework.controll.commands.HelpCommand;
import kadledav.adventure.framework.controll.commands.ShowInventoryCommand;
import kadledav.adventure.framework.controll.commands.TakeCommand;
import kadledav.adventure.framework.controll.commands.UseCommand;
import kadledav.adventure.framework.model.controll.GameWrapper;

public class CommandLineControll {
	
	protected PrintStream out;
	protected Scanner in;
	protected String gameName;
	protected Map<String, Command> commands = new HashMap<String, Command>();
	protected GameWrapper gameWrapper;

	public CommandLineControll(GameWrapper gameWrapper, PrintStream out, InputStream in, String gameName) {
		this.out = new PrintStream(out == null ? System.out : out);
		this.in = new Scanner((in == null ? System.in : in));
		this.gameName = gameName == null ? "" : gameName;
		this.gameWrapper = gameWrapper;
		initCommandMap();
	
	}

	private void initCommandMap() {
		commands.put(ControllConstants.HELP, new HelpCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.EXPLORE_LOCATION, new ExploreCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.GO_LOCATION, new GoCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.TAKE_ITEM, new TakeCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.DROP_ITEM, new DropCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.SHOW_INVENTORY, new ShowInventoryCommand(out, in, gameWrapper.getPlayer()));
		commands.put(ControllConstants.USE, new UseCommand(out, in, gameWrapper.getPlayer()));
	}

	public void startGame(){
		out.println("Hra \""+gameName+"\" zacala.");
		out.println("Zadany prikaz vzdy potvrdte entrem, pro napovedu pouzite prikaz: "+ControllConstants.HELP+"\n");
		
		Scanner in = new Scanner(System.in);  
		while(!gameWrapper.isPlayerWin()){
			String[] nextLine = in.nextLine().split("\\s+");
			Command command = commands.get(nextLine[0]);
			if(command!=null){
				command.execute(nextLine);
			}else{
				if (ControllConstants.EXIT.equalsIgnoreCase(nextLine[0])){
					break;
				} else {
					out.println("Takovy prikaz neexistuje\n");
				}
			}
		}
		if(gameWrapper.isPlayerWin()){
			out.print("Gratuluji vyhral jsi!!!");			
		}
		in.close();
	}
}
